import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Link } from 'dva/router';
import { Card, Form, Select, Button, Row, Col, Input, message, Badge, Divider, Modal } from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import NewForm from '../../components/UpLoadForm/NewForm';
import EditForm from '../../components/UpLoadForm/EditProgram';
import PubLish from '../../components/UpLoadForm/PubLish';
import styles from './Collections.less';

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['待审核', '已审核', '驳回'];
//const types = ['精确排挡', '简单排挡', '插播', '安保测试'];
const FormItem = Form.Item;
const { Option } = Select;
const CreateForm = Form.create()(NewForm);
const EidtprogramForm = Form.create()(EditForm);
const PubLishForm = Form.create()(PubLish);
@connect(({ program, loading, monitor }) => ({
  program,
  loading: loading.models.program,
  devList: monitor.devList,
}))
@Form.create()
export default class TableList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      selectedRows: [],
      selectRecord: '',
      formValues: {},
      pubVisible: false,
      operationkey: 'tab1',
      programDetail: {},
      editVisible: false,
    };
    this.method = 'pub';
  }
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'program/fetch',
      payload: { page: 1, pageSize: 10 },
    });
    dispatch({
      type: 'program/fetchProgType',
    });
    dispatch({
      type: 'monitor/fetchDevList',
    });
  }
  onFresh = () => {
    const { dispatch } = this.props;
    const postvalue = this.getFormValue();
    dispatch({
      type: 'program/fetch',
      payload: postvalue,
    });
  };

  getFormValue = () => {
    const { form } = this.props;
    const postvalue = {};
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const { entries } = Object;
      for (const [key, value] of entries(fieldsValue)) {
        if (value !== null && value !== undefined) {
          postvalue[key] = value;
        }
      }
    });
    return postvalue;
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const postvalue = this.getFormValue();

    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...postvalue,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'program/fetch',
      payload: params,
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch } = this.props;
    const postvalue = this.getFormValue();
    //console.log('values', postvalue);
    dispatch({
      type: 'program/fetch',
      payload: postvalue,
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
    //console.log('selectrows', this.state.selectedRows);
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleColse = () => {
    this.setState({
      pubVisible: false,
    });
  };

  mutipub = record => {
    this.setState({ pubVisible: true, selectRecord: record });
  };

  handleSelectChange = value => {
    this.setState({ type: value });
  };

  delProgram = () => {
    Modal.confirm({
      title: '确认删除',
      content: '确认要删这些广告么？删除后不可恢复',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        const { dispatch } = this.props;
        const { selectedRows } = this.state;
        //console.log('selectrows', this.state.selectedRows);
        if (selectedRows.length === 0) return;
        dispatch({
          type: 'program/remove',
          payload: {
            progIds: selectedRows,
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
      },
    });
  };
  onCopy = record => {
    this.props.dispatch({
      type: 'program/copy',
      payload: { progId: record.progId },
      callback: () => {
        message.success('复制成功，请在待审核列表中查看复制的节目');
        // this.card.current.onTabChange('tab1')
        this.setState({ operationkey: 'tab1' });
        this.props.dispatch({
          type: 'program/fetch',
          payload: { sorter: 'createTime_descend' },
        });
      },
    });
  };

  edit = record => {
    console.log('record', record)
    this.setState({ editVisible: true, programDetail: record });
  };
  handleEditModalVisible = flag => {
    this.setState({
      editVisible: !!flag,
    });
  };

  render() {
    const { program, loading, devList } = this.props;
    const { types } = program
    const { selectedRows, modalVisible, programDetail, editVisible } = this.state;
    const { getFieldDecorator } = this.props.form;
    const columns = [
      {
        title: '节目名称',
        dataIndex: 'progName',
      },
      {
        title: '类型',
        dataIndex: 'progType',

      },
      {
        title: '尺寸',
        dataIndex: 'progSize',
      },
      {
        title: '审核状态',
        dataIndex: 'progAuditStatus',
        render(val) {
          return <Badge status={statusMap[val]} text={status[val]} />;
        },
      },
      {
        title: '作者',
        dataIndex: 'progAuthor',
        sorter: true,
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        sorter: true,
      },
      {
        title: '操作',
        dataIndex: 'progId',
        render: (value, record, index) => {
          if (record.progAuditStatus === 0) {
            return (
              <Fragment>
                <a onClick={() => this.edit(record)}>编辑</a>
                <Divider type="vertical" />
                <Link
                  to={{
                    pathname: `/program/programconfig/${value}`,
                  }}
                >
                  配置
                </Link>
                {/* <Divider type="vertical" />
                <Link
                  to={{
                    pathname: `/program/programdetail/${encodeName}`,
                  }}
                >
                  审核
                </Link> */}
              </Fragment>
            );
          } else if (record.progAuditStatus === 2) {
            return (
              <Fragment>
                <Link
                  to={{
                    pathname: `/program/programconfig/${value}`,
                  }}
                >
                  配置
                </Link>
              </Fragment>
            );
          } else {
            return (
              <Fragment>
                <Link
                  to={{
                    pathname: `/program/programdetail/${value}`,
                  }}
                >
                  查看
                </Link>
                <Divider type="vertical" />
                <a onClick={() => this.onCopy(record)}>复制</a>
                <Divider type="vertical" />
                <a onClick={() => this.mutipub(record)}>发布</a>
                <Divider type="vertical" />
                <Link
                  to={{
                    pathname: `/devlog/tasklist/${value}`,
                  }}
                >
                  查看进度
                </Link>
              </Fragment>
            );
          }
        },
      },
    ];

    const extra = (
      <Row>
        <Form onSubmit={this.handleSearch}>
          <Row gutter={24}>
            <Col span={4}>
              <FormItem>
                {getFieldDecorator('progName', {
                  rules: [{ required: false, message: '请输入节目名称!' }],
                })(<Input placeholder="节目名称" />)}
              </FormItem>
            </Col>
            <Col span={4}>
              <FormItem>
                {getFieldDecorator('progAuthor', {
                  rules: [{ required: false, message: '请输入作者名称!' }],
                })(<Input placeholder="作者名称" />)}
              </FormItem>
            </Col>
            <Col span={4}>
              <FormItem>
                {getFieldDecorator('progSize', {
                  rules: [{ required: false, message: '请输入节目尺寸!' }],
                })(<Input placeholder="节目尺寸" />)}
              </FormItem>
            </Col>
            <Col span={3}>
              <FormItem>
                {getFieldDecorator('progAuditStatus')(
                  <Select allowClear="true" placeholder="审核状态" style={{ width: '100%' }}>
                    {status.map((item, index) => (
                      <Option value={index}>{item}</Option>
                    ))}
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={3}>
              <FormItem>
                {getFieldDecorator('progType')(
                  <Select allowClear="true" placeholder="节目类型" style={{ width: '100%' }}>
                    {program.progType.map((item, index) => (
                      <Option value={item.code}>{item.name}</Option>
                    ))}
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <Button
                type="primary"
                htmlType="submit"
                style={{ marginRight: 20 }}
                onClick={this.handleSearch}
              >
                查询
              </Button>
              <Button
                style={{ marginRight: 20 }}
                icon="plus"
                type="primary"
                onClick={() => this.handleModalVisible(true)}
              >
                添加
              </Button>
              <Button type="primary" style={{ marginRight: 20 }} onClick={this.delProgram}>
                删除
              </Button>
              <Button type="primary" onClick={this.onFresh}>
                刷新
              </Button>
            </Col>
          </Row>
        </Form>
        <PubLishForm
          devList={devList}
          history={this.props.history}
          record={this.state.selectRecord}
          handleColse={this.handleColse}
          modalVisible={this.state.pubVisible}
          dispatch={this.props.dispatch}
        />
      </Row>
    );

    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      handleEditModalVisible: this.handleEditModalVisible,
      handleSearch: this.handleSearch
    };

    const contentList = {
      tab1: (
        <StandardTable
          selectedRows={selectedRows}
          rowKey="progId"
          loading={loading}
          data={program}
          columns={columns}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      ),
    };
    return (
      <PageHeaderLayout>
        <Card title="节目列表">
          {extra}

          <div className={styles.tableList}>{contentList[this.state.operationkey]}</div>
        </Card>
        
        <CreateForm {...parentMethods} modalVisible={modalVisible} dispatch={this.props.dispatch} progType={program.progType} />
        <EidtprogramForm
          {...parentMethods}
          editMmodalVisible={editVisible}
          dispatch={this.props.dispatch}
          program={this.state.programDetail}
          progType={program.progType}
        />
      </PageHeaderLayout>
    );
  }
}
